package org.data.replay.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.data.replay.common.Result;
import org.data.replay.config.PlatformProperties;
import org.data.replay.dto.DataPoint;
import org.data.replay.dto.FaultResultModel;
import org.data.replay.dto.MeasurementResultDTO;
import org.data.replay.dto.ParameterDTO;
import org.data.replay.dto.QueryDataDTO;
import org.data.replay.service.DataReplayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据回放服务实现类 通过HTTP请求调用第三方平台接口
 *
 * @author DataReplay
 */
@Slf4j
@Service
public class DataReplayServiceImpl implements DataReplayService {
    
    @Autowired
    private PlatformProperties platformProperties;
    
    @Override
    public List<String> queryEquipmentList() {
        try {
            String url = platformProperties.getEquipmentListUrl();
            log.info("查询设备列表，请求URL: {}", url);
            
            // 发送GET请求
            HttpResponse response = HttpRequest.get(url).timeout(platformProperties.getTimeout()).execute();
            
            // 检查响应状态
            if (response.getStatus() != 200) {
                log.error("查询设备列表失败，HTTP状态码: {}", response.getStatus());
                throw new RuntimeException("查询设备列表失败，HTTP状态码: " + response.getStatus());
            }
            
            // 解析响应数据
            String responseBody = response.body();
            log.debug("查询设备列表响应: {}", responseBody);
            
            // 解析为Result类型
            Result<List<String>> result = JSON.parseObject(responseBody, new TypeReference<Result<List<String>>>() {
            });
            
            // 检查Result状态
            if (result == null) {
                log.warn("查询设备列表响应为空");
                return new ArrayList<>();
            }
            
            if (!result.isSuccess() || result.getCode() != 200) {
                String errorMsg = result.getMessage() != null ? result.getMessage() : "查询设备列表失败";
                log.error("查询设备列表失败，code: {}, message: {}", result.getCode(), errorMsg);
                throw new RuntimeException(errorMsg);
            }
            
            // 提取data字段
            List<String> equipmentList = result.getResult();
            if (equipmentList == null) {
                equipmentList = new ArrayList<>();
            }
            
            log.info("查询设备列表成功，数量: {}", equipmentList.size());
            return equipmentList;
            
        } catch (Exception e) {
            log.error("查询设备列表异常", e);
            throw new RuntimeException("查询设备列表异常: " + e.getMessage(), e);
        }
    }
    
    @Override
    public List<ParameterDTO> queryParametersByEquipment(String equipmentCode) {
        try {
            String url = platformProperties.getParameterQueryUrl();
            log.info("查询参数，设备编号: {}, 请求URL: {}", equipmentCode, url);
            
            // 发送GET请求，参数通过URL传递
            HttpResponse response = HttpRequest.get(url).form("equipmentCode", equipmentCode)
                    .timeout(platformProperties.getTimeout()).execute();
            
            // 检查响应状态
            if (response.getStatus() != 200) {
                log.error("查询参数失败，HTTP状态码: {}", response.getStatus());
                throw new RuntimeException("查询参数失败，HTTP状态码: " + response.getStatus());
            }
            
            // 解析响应数据
            String responseBody = response.body();
            log.debug("参数响应: {}", responseBody);
            
            // 解析为Result类型
            Result<List<ParameterDTO>> result = JSON.parseObject(responseBody,
                    new TypeReference<Result<List<ParameterDTO>>>() {
                    });
            
            // 检查Result状态
            if (result == null) {
                log.warn("查询参数响应为空");
                return new ArrayList<>();
            }
            
            if (!result.isSuccess() || result.getCode() != 200) {
                String errorMsg = result.getMessage() != null ? result.getMessage() : "查询参数失败";
                log.error("查询参数失败，code: {}, message: {}", result.getCode(), errorMsg);
                throw new RuntimeException(errorMsg);
            }
            
            // 提取data字段
            List<ParameterDTO> parameters = result.getResult();
            if (parameters == null) {
                parameters = new ArrayList<>();
            }
            
            log.info("查询参数成功，设备编号: {}, 参数数量: {}", equipmentCode, parameters.size());
            return parameters;
            
        } catch (Exception e) {
            log.error("查询参数异常，设备编号: {}", equipmentCode, e);
            throw new RuntimeException("查询参数异常: " + e.getMessage(), e);
        }
    }
    
    @Override
    public Map<String, List<DataPoint>> queryData(QueryDataDTO request) {
        try {
            String url = platformProperties.getQueryDataUrl();
            log.info("查询数据，请求URL: {}, 请求参数: {}", url, JSON.toJSONString(request));
            
            // 将请求对象转换为JSON字符串
            String requestBody = JSON.toJSONString(request);
            
            // 发送POST请求
            HttpResponse response = HttpRequest.post(url).body(requestBody)
                    .header("Content-Type", "application/json;charset=utf-8").timeout(platformProperties.getTimeout())
                    .execute();
            
            // 检查响应状态
            if (response.getStatus() != 200) {
                log.error("查询数据失败，HTTP状态码: {}", response.getStatus());
                throw new RuntimeException("查询数据失败，HTTP状态码: " + response.getStatus());
            }
            
            // 解析响应数据
            String responseBody = response.body();
            log.debug("数据响应: {}", responseBody);
            
            // 解析为Result类型
            Result<Map<String, List<DataPoint>>> result = JSONObject.parseObject(responseBody, Result.class);
            
            // 检查Result状态
            if (result == null) {
                log.warn("查询数据响应为空");
                return new HashMap<>();
            }
            
            if (!result.isSuccess() || result.getCode() != 200) {
                String errorMsg = result.getMessage() != null ? result.getMessage() : "查询数据失败";
                log.error("查询数据失败，code: {}, message: {}", result.getCode(), errorMsg);
                throw new RuntimeException(errorMsg);
            }
            // 提取data字段
            return result.getResult();
            
        } catch (Exception e) {
            log.error("查询数据异常，请求参数: {}", JSON.toJSONString(request), e);
            throw new RuntimeException("查询数据异常: " + e.getMessage(), e);
        }
    }
    
    @Override
    public Map<String, MeasurementResultDTO> queryMeasurement(QueryDataDTO request) {
        try {
            String url = platformProperties.getQueryMeasurementUrl();
            log.info("查询测量数据，请求URL: {}, 请求参数: {}", url, JSON.toJSONString(request));
            
            // 将请求对象转换为JSON字符串
            String requestBody = JSON.toJSONString(request);
            
            // 发送POST请求
            HttpResponse response = HttpRequest.post(url).header("Content-Type", "application/json;charset=utf-8")
                    .body(requestBody).timeout(platformProperties.getTimeout()).execute();
            
            // 检查响应状态
            if (response.getStatus() != 200) {
                log.error("查询测量数据失败，HTTP状态码: {}", response.getStatus());
                throw new RuntimeException("查询测量数据失败，HTTP状态码: " + response.getStatus());
            }
            
            // 解析响应数据
            String responseBody = response.body();
            log.debug("测量数据响应: {}", responseBody);
            
            // 解析为Result类型
            Result<Map<String, MeasurementResultDTO>> result = JSON.parseObject(responseBody,
                    new TypeReference<Result<Map<String, MeasurementResultDTO>>>() {
                    });
            
            // 检查Result状态
            if (result == null) {
                log.warn("查询测量数据响应为空");
                return new HashMap<>();
            }
            
            if (!result.isSuccess() || result.getCode() != 200) {
                String errorMsg = result.getMessage() != null ? result.getMessage() : "查询测量数据失败";
                log.error("查询测量数据失败，code: {}, message: {}", result.getCode(), errorMsg);
                throw new RuntimeException(errorMsg);
            }
            
            // 提取data字段
            Map<String, MeasurementResultDTO> measurementResults = result.getResult();
            if (measurementResults == null) {
                measurementResults = new HashMap<>();
            }
            
            log.info("查询测量数据成功，结果数量: {}", measurementResults.size());
            return measurementResults;
        } catch (Exception e) {
            log.error("查询测量数据异常，请求参数: {}", JSON.toJSONString(request), e);
            throw new RuntimeException("查询测量数据异常: " + e.getMessage(), e);
        }
    }
    
    @Override
    public List<FaultResultModel> queryFaultInfo(String unitCode, Date starTime, Date endTime) {
        try {
            // 格式化日期为字符串
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTimeStr = dateFormat.format(starTime);
            String endTimeStr = dateFormat.format(endTime);
            
            String faultQuery = platformProperties.getQueryFaultUrl();
            HttpResponse response = HttpRequest.get(faultQuery).form("unitCode", unitCode)
                    .form("startTime", startTimeStr).form("endTime", endTimeStr)
                    .timeout(platformProperties.getTimeout()).execute();
            
            // 检查响应状态
            if (response.getStatus() != 200) {
                log.error("查询参数失败，HTTP状态码: {}", response.getStatus());
                throw new RuntimeException("查询参数失败，HTTP状态码: " + response.getStatus());
            }
            
            // 解析响应数据
            String responseBody = response.body();
            log.debug("故障数据响应: {}", responseBody);
            
            // 解析为Result类型
            Result<List<FaultResultModel>> result = JSON.parseObject(responseBody,
                    new TypeReference<Result<List<FaultResultModel>>>() {
                    });
            
            // 提取data字段
            List<FaultResultModel> faultInfo = result.getResult();
            if (faultInfo == null) {
                faultInfo = new ArrayList<>();
            }
            
            return faultInfo;
        } catch (Exception e) {
            log.error("查询故障信息异常", e);
            throw new RuntimeException("查询故障信息异常: " + e.getMessage(), e);
        }
    }
}
